package com.example.demo.controller;

import com.alipay.api.AlipayApiException;
import com.example.demo.dto.ResponseResult;
import com.example.demo.service.AlipayService;
import com.example.demo.service.OrderService;
import com.example.demo.entity.Order;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private OrderService orderService;

    @PostMapping("/pay")
    public ResponseResult<Map<String, String>> alipayPay(
            @RequestParam("WIDout_trade_no") String outTradeNo,
            @RequestParam("WIDsubject") String subject,
            @RequestParam("WIDtotal_amount") String totalAmount,
            @RequestParam("WIDbody") String body
            ) throws IOException, AlipayApiException {

        String payForm = alipayService.processPayment(outTradeNo, subject, totalAmount, body);
        Map<String, String> result = new HashMap<>();
        result.put("payForm", payForm);
        return new ResponseResult<>(200, "success", result);
    }

    // 新增：直接通过订单号访问支付页面
    @GetMapping("/pay/{orderNo}")
    public String payByOrderNo(@PathVariable String orderNo) throws IOException, AlipayApiException {
        // 根据订单号查询订单信息
        Order order = orderService.getOrder(orderNo);
        if (order == null) {
            return "订单不存在";
        }

        // 调用支付服务生成支付表单

        return alipayService.processPayment(
            order.getOrderNo(),
            "服务购买",
            String.valueOf(order.getAmount()),
            "购买服务"
        );
    }

    // 订单状态查询接口，前端用此接口查询支付结果
    @GetMapping("/queryOrderStatus")
    public ResponseResult<Map<String, Object>> queryOrderStatus(@RequestParam("outTradeNo") String outTradeNo) {
        try {
            return new ResponseResult<>(200, "success", alipayService.queryOrderStatus(outTradeNo));
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/notify")
    public String handleNotify(@RequestParam Map<String, String> params) {
        return alipayService.handleNotify(params);
    }

    // 支付结果展示页面
    @GetMapping("/result")
    public String payResult(@RequestParam(required = false) String outTradeNo) {
        String html;
        if (outTradeNo != null && !outTradeNo.isEmpty()) {
            // 这里假设订单状态1为已支付
            com.example.demo.entity.Order order = orderService.getOrder(outTradeNo);
            if (order != null && order.getStatus() == 2) {
                html = "<html><body style='text-align:center;margin-top:80px;'><h2>支付成功！</h2><p>订单号：" + outTradeNo + "</p><p>请返回App或浏览器继续操作。</p></body></html>";
            } else {
                html = "<html><body style='text-align:center;margin-top:80px;'><h2>支付未完成</h2><p>订单号：" + outTradeNo + "</p><p>如有疑问请联系客服。</p></body></html>";
            }
        } else {
            html = "<html><body style='text-align:center;margin-top:80px;'><h2>未查询到订单信息</h2></body></html>";
        }
        return html;
    }
}
